import { Router } from "express";
import { apiPagelist, apiPlayurl } from "@/api-bili/index";

import type { Request } from "express";

export const videoRouter = Router().get(
  "/video",
  async (req: Request<{}, {}, {}, { bvid?: string }>, res) => {
    try {
      const { bvid } = req.query;
      if (!bvid) {
        throw new Error("没有找到参数 bvid");
      }

      const cid = await getCid(bvid);
      let url = await getUrl(bvid, cid);

      /** 替换为国内CDN */
      const upgcxcodeRegex = /(https?:\/\/)(.*?)(\/upgcxcode\/)/;
      if (upgcxcodeRegex.test(url)) {
        url = url.replace(
          upgcxcodeRegex,
          "https://upos-sz-mirrorali.bilivideo.com/upgcxcode/"
        );
      }

      res.json(successResponse({ url }));
    } catch (e) {
      let msg = "反正有错误";
      if (e instanceof Error) {
        msg = e.message;
      }
      res.json(errorResponse(msg));
    }
  }
);

/** 成功返回 */
function successResponse(data: Record<string, any>) {
  return {
    code: 200,
    msg: "请求成功",
    data,
  };
}

/** 错误返回 */
function errorResponse(msg: string) {
  return {
    code: 400,
    msg,
  };
}

async function getCid(bvid: string) {
  const data = await apiPagelist({ bvid });
  if (data.code === 0) {
    return data.data[0].cid;
  } else {
    throw new Error(`获取cid失败：${data.message}`);
  }
}

async function getUrl(bvid: string, cid: number) {
  const data = await apiPlayurl({
    bvid,
    cid,
    qn: 80,
    fnval: 1,
    platform: "html5", // 无需referer鉴权
    high_quality: 1,
  });
  if (data.code === 0) {
    return data.data.durl[0].url;
  } else {
    throw new Error(`获取视频地址失败：${data.message}`);
  }
}
